package com.bxd.baodan.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.activity.SearchProduceActivity;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.item.ProductSelectBaseBean;
import com.bxd.baodan.item.ProductSelectBean;
import com.bxd.baodan.list.CheXianFragment;
import com.bxd.baodan.list.ProductSelectFragment;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.widget.PagerSlidingTabStrip;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

public class ProductCenterFragment extends BaseFragment {
    private View v;
    private ViewPager viewPager;
    private List<BaseFragment> fragmentList = new ArrayList<BaseFragment>();
    private FragmentPagerAdapter pagerAdapter;
    private List<ProductSelectBean.SelectDataBean> selectDataBeanList = new ArrayList<>();
    PagerSlidingTabStrip tabs;
    private TextView search;
    public int position = -1;


    public static ProductCenterFragment getInstance(int position) {
        ProductCenterFragment fragmentA = new ProductCenterFragment();
        fragmentA.position = position;
        return fragmentA;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (v == null) {
            v = inflater.inflate(R.layout.fragment_product_center_sticky, container, false);
        }
        ViewGroup viewGroup = (ViewGroup) v.getParent();
        if (viewGroup != null) {
            viewGroup.removeAllViewsInLayout();
        }


        initView(v);

        return v;


    }

    private void initView(View view) {

        view.setPadding(view.getPaddingLeft(), view.getPaddingTop() + getStatusBarHeight(),
                view.getPaddingRight(), view.getPaddingBottom());

        search = (TextView) view.findViewById(R.id.edit_search);


        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                MobclickAgent.onEvent(App.getContext(), "v6_1_3_CP_ss");
                openActivity(SearchProduceActivity.class);
            }
        });



        setFragmentAdapter();

        viewPager = (ViewPager) view.findViewById(R.id.id_stickynavlayout_viewpager);
        tabs = (PagerSlidingTabStrip) view.findViewById(R.id.id_stickynavlayout_indicator);
        viewPager.setAdapter(pagerAdapter);
        tabs.setViewPager(viewPager);

        getData();


        tabs.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {


            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


    }

    private void getData() {
        getHotWord();
        getSortData();
    }

    private void setFragmentAdapter() {
        pagerAdapter = new FragmentPagerAdapter(getChildFragmentManager()) {

            @Override
            public int getCount() {
                return selectDataBeanList.size();
            }

            @Override
            public Fragment getItem(int arg0) {
                return fragmentList.get(arg0);
            }

            @Override
            public CharSequence getPageTitle(int position) {
                // FIXME: 18/1/26 解决tab宽度的问题
                return "  "+selectDataBeanList.get(position).name+"  ";
            }
        };
    }

    private void getSortData() {
        final NetUtil sortNet = new NetUtil(context, JsonApi.PRODUCT_CONDITION);
        sortNet.postRequest("加载中", new NetUtil.RequestStringListener() {
            @Override
            public void onComplete(String result) {
                initData(result);
            }


        });
    }

    private void initData(String result) {

        ProductSelectBaseBean bean = new Gson().fromJson(result, ProductSelectBaseBean.class);


        List<ProductSelectBean.SelectDataBean> data = bean.data.list;
        selectDataBeanList.clear();
        selectDataBeanList.addAll(data);



        fragmentList.clear();

        for (int i = 0; i < selectDataBeanList.size(); i++) {
            ProductSelectBean.SelectDataBean selectDataBean = selectDataBeanList.get(i);

            if (selectDataBean.name.equals("车险")) {
                CheXianFragment fragment = CheXianFragment.getInstance(selectDataBean);
                fragmentList.add(fragment);

            } else {
                ProductSelectFragment fragment = ProductSelectFragment.getInstance(selectDataBean);
                fragmentList.add(fragment);
            }



        }

        setTabsValue();
        pagerAdapter.notifyDataSetChanged();

        tabs.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                if (position != -1) {
                    viewPager.setCurrentItem(position);
                    position = -1;
                }
            }
        });
    }


    private void setTabsValue() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        // 设置Tab底部选中的指示器Indicator的高度
        tabs.setIndicatorHeight(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2.5f, dm));

        // 设置Tab底部选中的指示器 Indicator的颜色
        tabs.setIndicatorColorResource(R.color.green_lab);
        //设置指示器Indicatorin是否跟文本一样宽，默认false
        tabs.setIndicatorinFollowerTv(false);
        //设置小红点提示，item从0开始计算，true为显示，false为隐藏
        //        tabs.setMsgToast(2, true);
        //设置红点滑动到当前页面自动消失,默认为true
        tabs.setMsgToastPager(true);
        //设置Tab标题文字的颜色
        tabs.setTextColor(getResources().getColor(R.color.black));
        // 设置Tab标题文字的大小
        tabs.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 14, dm));
        // 设置选中的Tab文字的颜色
        tabs.setSelectedTextColorResource(R.color.green_lab);
        //设置Tab底部分割线的高度
        tabs.setUnderlineHeight(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 0.5f, dm));
        //设置Tab底部分割线的颜色
        tabs.setUnderlineColorResource(R.color.line_f7);
        // 设置点击某个Tab时的背景色,设置为0时取消背景色tabs.setTabBackground(0);
        //        tabs.setTabBackground(R.drawable.bg_tab);
        tabs.setTabBackground(0);
        // 设置Tab是自动填充满屏幕的
        tabs.setShouldExpand(false);


    }

    public void toFree() {

        for (int i = 0; i < selectDataBeanList.size(); i++) {
            if (selectDataBeanList.get(i).name.equals("免费")) {
                viewPager.setCurrentItem(i);
                break;
            }

        }


    }

    public void toYanxuan() {
        viewPager.setCurrentItem(0);
    }



    public void getHotWord() {
        NetUtil netUtil = new NetUtil(getActivity(), JsonApi.THINK_WORD);
        netUtil.setParams("inputPos", "product");
        netUtil.postRequest("", new NetUtil.DataListener() {
            @Override
            public void onComplete(String data) {
                String key = JSONUtil.getData("keyword", data);
                search.setHint(key);
            }
        });
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (fragmentList.size()==0 ||selectDataBeanList.size() == 0 ) {
                getData();
            }

        }

    }


}
